const db = require("../common/db/index")

module.exports = {
  // 添加弹幕
  add(user_id, content, color, speed, position, createAt, status) {
    return new Promise(async (resolve, reject) => {
      try {
        const sql = 'INSERT INTO pre_danmu (user_id, content, color, speed, position, createAt, status) VALUES (?, ?, ?, ?, ?, ?, ?)';
        const result = await db.query(sql, [user_id, content, color || '#FFFFFF', speed || 5, position || 0, createAt, status || 'published']);
        resolve({
          code: 200,
          msg: "弹幕发送成功",
          result: result
        });
      } catch (err) {
        reject({
          code: 500,
          msg: "弹幕发送失败",
          err: err
        });
      }
    });
  },

  // 获取弹幕列表（支持分页）
  getList(page_num, page_size) {
    return new Promise(async (resolve, reject) => {
      try {
        // 先获取总数
        const countSql = 'SELECT count(*) as total FROM pre_danmu WHERE status = ?';
        const countResult = await db.query(countSql, ['published']);
        const total = countResult[0].total;

        // 分页查询
        let page_num2 = ((parseInt(page_num) - 1) * parseInt(page_size));
        let page_size2 = parseInt(page_size);
        const sql = `
                    SELECT d.*, u.username, u.imgUrl 
                    FROM pre_danmu d 
                    LEFT JOIN pre_user u ON d.user_id = u.id 
                    WHERE d.status = ?
                    ORDER BY d.createAt DESC 
                    LIMIT ${page_num2}, ${page_size2}
                `;
        const data = await db.query(sql, ['published']);

        resolve({
          code: 200,
          msg: "获取弹幕列表成功",
          total: total,
          data: data
        });
      } catch (err) {
        reject({
          code: 500,
          msg: "获取弹幕列表失败",
          err: err
        });
      }
    });
  },

  // 获取所有弹幕（不分页，用于弹幕显示）
  getAll() {
    return new Promise(async (resolve, reject) => {
      try {
        const sql = `
                    SELECT d.*, u.username, u.imgUrl 
                    FROM pre_danmu d 
                    LEFT JOIN pre_user u ON d.user_id = u.id 
                    WHERE d.status = ?
                    ORDER BY d.createAt DESC
                `;
        const data = await db.query(sql, ['published']);

        resolve({
          code: 200,
          msg: "获取弹幕列表成功",
          data: data
        });
      } catch (err) {
        reject({
          code: 500,
          msg: "获取弹幕列表失败",
          err: err
        });
      }
    });
  },

  // 删除弹幕（软删除，修改状态）
  delete(id, user_id) {
    return new Promise(async (resolve, reject) => {
      try {
        // 先检查弹幕是否存在且属于该用户
        const checkSql = 'SELECT * FROM pre_danmu WHERE id = ? AND user_id = ?';
        const checkResult = await db.query(checkSql, [id, user_id]);

        if (checkResult.length === 0) {
          resolve({
            code: 403,
            msg: "无权删除此弹幕"
          });
          return;
        }

        // 软删除：修改状态为deleted
        const sql = 'UPDATE pre_danmu SET status = ? WHERE id = ?';
        const result = await db.query(sql, ['deleted', id]);

        resolve({
          code: 200,
          msg: "删除弹幕成功",
          result: result
        });
      } catch (err) {
        reject({
          code: 500,
          msg: "删除弹幕失败",
          err: err
        });
      }
    });
  },

  // 获取用户的所有弹幕
  getUserDanmus(user_id, page_num, page_size) {
    return new Promise(async (resolve, reject) => {
      try {
        const countSql = 'SELECT count(*) as total FROM pre_danmu WHERE user_id = ? AND status = ?';
        const countResult = await db.query(countSql, [user_id, 'published']);
        const total = countResult[0].total;

        let page_num2 = ((parseInt(page_num) - 1) * parseInt(page_size));
        let page_size2 = parseInt(page_size);
        const sql = `
                    SELECT d.*
                    FROM pre_danmu d 
                    WHERE d.user_id = ? AND d.status = ? 
                    ORDER BY d.createAt DESC 
                    LIMIT ${page_num2}, ${page_size2}
                `;
        const data = await db.query(sql, [user_id, 'published']);

        resolve({
          code: 200,
          msg: "获取用户弹幕成功",
          total: total,
          data: data
        });
      } catch (err) {
        reject({
          code: 500,
          msg: "获取用户弹幕失败",
          err: err
        });
      }
    });
  },

  // 获取所有弹幕列表（管理员用）
  getAllDanmus(page_num, page_size, keyword) {
    return new Promise(async (resolve, reject) => {
      try {
        let countSql = 'SELECT count(*) as total FROM pre_danmu d LEFT JOIN pre_user u ON d.user_id = u.id WHERE 1=1';
        let sql = `
          SELECT d.*, u.username 
          FROM pre_danmu d 
          LEFT JOIN pre_user u ON d.user_id = u.id 
          WHERE 1=1
        `;
        let params = [];

        // 如果有搜索关键词，添加搜索条件
        if (keyword && keyword.trim()) {
          const keywordParam = `%${keyword.trim()}%`;
          countSql += ' AND (d.content LIKE ? OR u.username LIKE ?)';
          sql += ' AND (d.content LIKE ? OR u.username LIKE ?)';
          params = [keywordParam, keywordParam];
        }

        // 获取总数
        const countResult = await db.query(countSql, params);
        const total = countResult[0].total;

        // 分页查询
        let page_num2 = ((parseInt(page_num) - 1) * parseInt(page_size));
        let page_size2 = parseInt(page_size);
        sql += ` ORDER BY d.createAt DESC LIMIT ${page_num2}, ${page_size2}`;

        const data = await db.query(sql, params);

        resolve({
          code: 200,
          msg: "获取弹幕列表成功",
          total: total,
          data: data
        });
      } catch (err) {
        reject({
          code: 500,
          msg: "获取弹幕列表失败",
          err: err
        });
      }
    });
  },

  // 管理员删除弹幕（硬删除）
  adminDelete(id) {
    return new Promise(async (resolve, reject) => {
      try {
        const sql = 'DELETE FROM pre_danmu WHERE id = ?';
        const result = await db.query(sql, [id]);

        resolve({
          code: 200,
          msg: "删除弹幕成功",
          result: result
        });
      } catch (err) {
        reject({
          code: 500,
          msg: "删除弹幕失败",
          err: err
        });
      }
    });
  }
}

